<template>
	<view class="coupon" :style="{paddingTop:navHeight}">
		<view class="top-nav-box" :style="{height:navHeight, paddingTop:statusBarHeight}">
			<image v-if="share==1||pageNum<=1" class="top-nav-back" src="../../../static/images/icon_float_home.png"
				@click="goHome"></image>
			<image v-else class="top-nav-back" src="../../../static/images/icon_user_back.png" @click="getback"></image>
		</view>
		<view class="coupon-banner" :style="{marginTop:marginTop}">
			<image src="../../static/coupon_center_bg.png" style="width: 100%;" mode="widthFix"></image>
		</view>
		<view class="list-title" :style="{top:statusBarHeight}">
			<view :style="{height:statusBarHeight,display:'flex',justifyContent: 'center',alignItems: 'center'}">
				<image src="../../static/coupon_center_title.png" style="height: 54rpx;" mode="heightFix"></image>
			</view>
		</view>
		<view class="list-box" :style="{top:navHeight}">
			<view class="coupon-hot bg-white">
				<view class="coupon-hot-head">
					<text class="coupon-hot-title">限时抢券</text>
					<view class="coupon-hot-time" v-if="datetime>0">距离活动开始
						<text class="time-box">{{hour<10?'0'+hour:hour}}</text>
						<text class="time-box">{{minute<10?'0'+minute:minute}}</text>
						<text class="time-box">{{second<10?'0'+second:second}}</text>
					</view>
				</view>
				<template v-if="timeList.length>0">
					<scroll-view :scroll-left="scrollLeft" scroll-x="true" class="coupon-time-wrap">
						<view class="coupon-time-list">
							<view class="coupon-time-cell" :class="{'active':item.type==2||item.fullDate==curDate}"
								v-for="item in timeList" :key="item.fullDate" @click="getCouponListFun(item.fullDate)">
								<text class="coupon-time-text">{{item.time}}</text>
								<view class="coupon-time-status">
									<image v-if="item.type==2" src="../../static/icon_coupon_hot.png"
										style="width: 19rpx;height: 22rpx;margin-right: 8rpx;vertical-align: -2rpx;">
									</image>{{item.dateText}}
								</view>
							</view>
						</view>
					</scroll-view>
					<view class="coupon-item-wrap">
						<view class="coupon-item-list">
							<view class="coupon-item-box"
								@click="goUrl((item.status_text_value==4)?'/bundle/pages/get_coupon_detail/get_coupon_detail?id='+item.ccl_id:'/bundle/pages/get_coupon_guide/get_coupon_guide?id='+item.id)"
								v-for="(item,index) in couponListLimeted" :key="index">
								<view class="coupon-item-title">
									<image v-if="item.type==0" src="../../static/icon_coupon_book.png"
										style="width: 27rpx;height: 20rpx;margin-right: 6rpx;vertical-align: -4rpx;">
									</image>
									<image v-else-if="item.type==1" src="../../static/icon_coupon_gift.png"
										style="width: 22rpx;height: 22rpx;margin-right: 6rpx;vertical-align: -5rpx;">
									</image>
									<image v-else src="../../static/icon_coupon_coffee.png"
										style="width: 24rpx;height: 21rpx;margin-right: 6rpx;vertical-align: -4rpx;">
									</image>
									{{item.type==0?"图书":item.type==1?"文创":"咖啡"}}
								</view>
								<view class="coupon-item-money">
									<text style="font-size: 63rpx;">{{item.money}}</text>
									<text style="font-size: 22rpx;">元</text>
								</view>
								<view class="coupon-item-tips">{{item.use_min>0?"满"+item.use_min+"元可用":"无门槛"}}</view>
								<view class="coupon-btn-box">
									<view class="coupon-item-btn"
										v-if="item.status_text_value==2||item.status_text_value==5||item.status_text_value==6"
										@tap.stop="grabCouponFun(item)">
										{{item.status_text}}
									</view>
									<view class="coupon-item-btn" v-else>{{item.status_text}}</view>
								</view>
							</view>
						</view>
					</view>
				</template>
				<view class="coupon-hot-none" v-else>
					<text>本期抢券活动已结束，敬请期待下期活动开始~</text>
				</view>
			</view>
			<view class="coupon-list bg-white" v-if="couponListOnline.length>0">
				<view class="coupon-list-titel">云店专享优惠券</view>
				<coupon-list :list="couponListOnline" :if-act="grabCouponKey" :btn-type="0"
					@refresh="refresh"></coupon-list>
			</view>
			<view class="coupon-list bg-white" v-if="couponListOffline.length>0">
				<view class="coupon-list-titel">线下门店券</view>
				<coupon-list :list="couponListOffline" :if-act="grabCouponKey" :btn-type="0"
					@refresh="refresh"></coupon-list>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	import Cache from "@/utils/cache";
	import {
		BACK_URL
	} from "@/config/cachekey";
	import {
		getCouponListTime,
		getCouponList,
		getCouponListOther,
		grabCoupon,
		checkGrabStatus
	} from "@/api/activity";
	import {
		getIsMember
	} from '@/api/user';
	export default {
		data() {
			return {
				timeList: [],
				couponListLimeted: [],
				couponList: [],
				couponListOffline: [],
				couponListOnline: [],
				timer: null,
				datetime: 0,
				hour: '0',
				minute: '0',
				second: '0',
				curDate: '',
				checkStatusTimer: null,
				checkStatusCount: 0,
				grabCouponKey: true,
				scrollLeft: 0,
				contentLeft: 0,
				activeLeft: 0,
				share: 0,
				pageNum: 1
			};
		},

		onLoad() {
			const options = this.$Route.query;
			this.share = options.share;
			this.pageNum = getCurrentPages().length;
			this.getMemberInfoFun()
		},
		computed: {
			...mapGetters(['token', 'sysInfo']),
			statusBarHeight() {
				return this.sysInfo.statusBarHeight + 'px'
			},
			navHeight() {
				return this.sysInfo.navHeight + 'px'
			},
			marginTop() {
				return '-' + (this.sysInfo.navHeight) + 'px'
			},
		},
		methods: {
			async getMemberInfoFun() {
				const {
					data,
					code
				} = await getIsMember(this.token);
				if (code == -1) {
					Cache.set(BACK_URL, '/bundle/pages/get_coupon/get_coupon')
					uni.navigateTo({
						url: '/pages/login/login'
					});
					uni.reLaunch({
						url: '/pages/login/login',
					})
				} else if (code == 1) {
					this.getCouponListTimeFun();
					this.getCouponListOtherFun();
				} else if (code == 0) {
					Cache.set(BACK_URL, '/bundle/pages/get_coupon/get_coupon')
					uni.switchTab({
						url: '/pages/member_centre/member_centre'
					});
					uni.reLaunch({
						url: '/pages/member_centre/member_centre',
					})
				}
			},
			getNowDate() {
				let date = new Date();
				let year = date.getFullYear(),
					month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1,
					day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
				return year + "-" + month + "-" + day
			},
			setTime() {
				if (this.datetime > 0) {
					this.hour = Math.floor(this.datetime / 3600)
					this.minute = Math.floor((this.datetime / 60) % 60)
					this.second = Math.floor(this.datetime % 60)
					this.getTime();
				}
			},
			getTime() {
				var self = this
				clearInterval(this.timer)
				this.timer = setInterval(() => {
					if (self.hour === 0) {
						if (self.minute !== 0 && self.second === 0) {
							self.second = 59
							self.minute -= 1
						} else if (self.minute === 0 && self.second === 0) {
							self.second = 0
							clearInterval(self.timer)
							self.getCouponListTimeFun();
						} else {
							self.second -= 1
						}
					} else {
						if (self.minute !== 0 && self.second === 0) {
							self.second = 59
							self.minute -= 1
						} else if (self.minute === 0 && self.second === 0) {
							self.hour -= 1
							self.minute = 59
							self.second = 59
						} else {
							self.second -= 1
						}
					}
				}, 1000)
			},
			getCouponListTimeFun() {
				getCouponListTime().then((res) => {
					if (res.code == 1) {
						let list = res.data;
						let currentDate = "";
						for (let i = 0; i < list.length; i++) {
							if (i == 0) {
								this.datetime = ((new Date(list[0]).getTime()) - (new Date().getTime())) / 1000;
								if (this.datetime > 0) {
									this.setTime();
									currentDate = list[i];
								}
							}
							let date = this.getNowDate() == list[i].split(" ")[0] ? "" : list[i].split(" ")[0];
							let type = 0,
								dateText = "";
							if (date == "") {
								if ((new Date(list[i]).getTime()) - (new Date().getTime()) > 0) {
									type = 1;
									dateText = "即将开始";
								} else {
									if (i < (list.length - 1)) {
										if ((new Date(list[i + 1]).getTime()) - (new Date().getTime()) <= 0) {
											type = 3;
											dateText = "已结束";
										} else {
											type = 2;
											dateText = "正在热抢";
											currentDate = list[i];
										}
									} else {
										type = 2;
										dateText = "正在热抢";
										currentDate = list[i];
									}
								}
							} else {
								dateText = "明天开抢"
							}
							this.timeList.push({
								type: type,
								dateText: dateText,
								time: list[i].split(" ")[1],
								fullDate: list[i]
							})
						}
						setTimeout(() => {
							this.initContentLeft()
						}, 100)
						if (currentDate) {
							this.getCouponListFun(currentDate);
						}
					} else {
						this.$toast({
							title: res.msg
						});
					}
				});
			},
			getCouponListFun(time) {
				if (time) {
					this.curDate = time
				}
				getCouponList(this.curDate).then((res) => {
					if (res.code == 1) {
						this.couponListLimeted = res.data;
					} else {
						this.$toast({
							title: res.msg
						});
					}
				});
			},
			getCouponListOtherFun() {
				getCouponListOther().then((res) => {
					if (res.code == 1) {
						this.couponListOffline = res.data.offline ? res.data.offline : [];
						this.couponListOnline = res.data.online ? res.data.online : [];
					} else {
						this.$toast({
							title: res.msg
						});
					}
				});
			},
			async grabCouponFun(item) {
				console.log("grabCouponKey", this.grabCouponKey);
				if (this.grabCouponKey) {
					this.grabCouponKey = false;
					let res = await grabCoupon(item.id);
					if (res.code == 1) {
						this.checkStatusCount = 0
						this.checkGrabStatusFun(res.data.job_id)
					} else {
						this.grabCouponKey = true;
						this.$toast({
							title: res.msg
						});
						if (res.data.status == "need_mobile") {
							setTimeout(() => {
								this.$Router.push({
									path: "/bundle/pages/user_profile/user_profile"
								})
							}, 2000)
						}
					}
				}
			},
			async checkGrabStatusFun(id) {
				let that = this;
				let resStatus = await checkGrabStatus(id);
				clearTimeout(that.checkStatusTimer)
				that.checkStatusCount++;
				if (resStatus.code != 1 && that.checkStatusCount < 5) {
					if (resStatus.data.status == "pending") {
						this.$toast({
							title: resStatus.msg
						});
						that.checkStatusTimer = setTimeout(() => {
							that.checkGrabStatusFun(id);
						}, 1000)
					} else if (resStatus.data.status == "fail") {
						this.$toast({
							title: resStatus.msg
						});
						that.checkStatusTimer = null;
						this.grabCouponKey = true;
						this.getCouponListFun();
					}
				} else {
					this.$toast({
						title: resStatus.msg
					});
					that.checkStatusTimer = null;
					this.grabCouponKey = true;
					this.getCouponListFun();
				}
			},
			refresh() {
				this.couponListOffline = [];
				this.couponListOnline = [];
				this.getCouponListOtherFun(); // 再刷新列表数据
			},
			getback() {
				if (this.share) {
					uni.switchTab({
						url: "/pages/index/index"
					});
				} else {
					//#ifdef H5
					this.$router.go(-1); //返回上一层
					//#endif

					//#ifdef MP-WEIXIN
					uni.navigateBack({
						delta: 1
					});
					//#endif	
				}
			},
			goHome() {
				uni.switchTab({
					url: "/pages/index/index"
				});
			},
			goUrl(url) {
				this.$Router.push({
					path: url
				})
			},
			initDomLeft() {
				uni.createSelectorQuery()
					.in(this)
					.select('.active')
					.boundingClientRect(data => {
						if (data) {
							this.activeLeft = data.left
							let left = this.activeLeft - this.contentLeft;
							if (left > 0) {
								this.scrollLeft = left;
							}
						}
					})
					.exec();
			},
			initContentLeft() {
				uni.createSelectorQuery()
					.in(this)
					.select('.coupon-time-list')
					.boundingClientRect(data => {
						if (data) {
							this.contentLeft = data.left;
							console.log("contentLeft", data.left)
							this.initDomLeft();
						}
					})
					.exec();
			}
		},
		async onShareAppMessage() {
			return {
				title: "领券中心",
				path: "/bundle/pages/get_coupon/get_coupon?share=1",
			};
		},
	};
</script>
<style lang="scss">
	.coupon {
		position: fixed;
		width: 100%;
		height: 100%;

		.coupon-banner {
			width: 100%;
			text-align: center;
		}

		.top-nav-box {
			position: fixed;
			display: flex;
			align-items: center;
			justify-content: space-between;
			width: 100%;
			padding-left: 32rpx;
			padding-right: 200rpx;
			top: 0;
			z-index: 1;

			.top-nav-back {
				width: 58rpx;
				height: 58rpx;
			}
		}

		.list-title {
			position: fixed;
			width: 100%;
		}

		.list-box {
			position: fixed;
			width: 100%;
			bottom: 0;
			overflow-y: scroll;
			overflow-x: hidden;

			.coupon-hot {
				margin: 50rpx 20rpx 0;
				padding: 25rpx;
				border-radius: 16rpx;

				.coupon-hot-head {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.coupon-hot-title {
						font-size: 42rpx;
						font-weight: 700;
						font-style: italic;
						color: #f5533c;
					}

					.coupon-hot-time {
						font-size: 24rpx;
						color: #f66c41;

						.time-box {
							display: inline-block;
							width: 36rpx;
							height: 32rpx;
							margin-left: 10rpx;
							line-height: 30rpx;
							background-color: #f66c41;
							border-radius: 6rpx;
							color: #fff;
							text-align: center;
						}
					}
				}

				.coupon-time-wrap {
					width: 100%;
					margin-top: 30rpx;
					overflow-x: auto;

					.coupon-time-list {
						display: flex;
						flex-direction: row;
						flex-wrap: nowrap;

						.coupon-time-cell {
							width: 168rpx;
							text-align: center;
							flex-grow: 0;
							flex-shrink: 0;

							.coupon-time-text {
								font-size: 42rpx;
								font-weight: 700;
							}

							.coupon-time-status {
								font-size: 24rpx;
								color: #9e9e9e;
							}

							&.active .coupon-time-text,
							&.active .coupon-time-status {
								color: #f65a41;
							}
						}
					}
				}

				.coupon-item-wrap {
					width: 100%;
					margin-top: 30rpx;
					overflow-x: auto;

					.coupon-item-list {
						display: flex;
						flex-direction: row;
						flex-wrap: nowrap;

						.coupon-item-box {
							display: flex;
							flex-direction: column;
							flex-wrap: nowrap;
							justify-content: space-between;
							width: 189rpx;
							height: 238rpx;
							margin-right: 20rpx;
							background: url(../../static/coupon_item_bg.png) no-repeat;
							background-size: contain;
							text-align: center;

							.coupon-item-title {
								height: 54rpx;
								font-size: 21rpx;
								line-height: 54rpx;
							}

							.coupon-item-money {
								height: 70rpx;
								color: #f14023;
							}

							.coupon-item-tips {
								font-size: 21rpx;
								color: #b29984;
							}

							.coupon-btn-box {
								height: 80rpx;
								line-height: 80rpx;
								text-align: center;
								align-items: center;

								.coupon-item-btn {
									display: inline-block;
									width: 132rpx;
									height: 45rpx;
									border: solid 1px #fff;
									border-radius: 45rpx;
									font-size: 25rpx;
									color: #fff;
									line-height: 40rpx;
									text-align: center;
								}
							}

						}
					}
				}

				.coupon-hot-none {
					display: flex;
					margin-top: 30rpx;
					align-items: center;
					font-size: 28rpx;
				}
			}

			.coupon-list {
				margin: 20rpx;
				padding: 25rpx;
				border-radius: 16rpx;

				.coupon-list-titel {
					font-size: 35rpx;
					font-weight: 700;
				}
			}
		}
	}
</style>